package com.appinterfacelite.service.impl;

import com.appinterfacelite.entity.Home_userEntity;
import com.appinterfacelite.entity.Homepage_detailsEntity;
import com.appinterfacelite.service.PermissionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 更新用户菜单实现类
 */
@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    RestTemplate restTemplate;
    @Autowired
    Home_userServiceImpl home_userService;
    @Autowired
    Homepage_detailsServiceImpl homepage_detailsService;

    @Value("${cosmo.ip}")
    public String ip;
    @Value("${cosmo.port}")
    public String port;

    /**
     * 查询所有nodeId
     *
     * @param userId
     * @param token
     * @return
     */
    @Override
    public JSONObject permissionNodeId(String userId, String token) {
        //查询所有nodeId
        List<Homepage_detailsEntity> homepage_detailsEntityList = homepage_detailsService.list();
        //设置返回的nodeId列表变量
        List<Map> returnList = new ArrayList<>();
        //循环请求接口
        for (int i = 0; i < homepage_detailsEntityList.size(); i++) {
            String nodeId = homepage_detailsEntityList.get(i).getNodeId();
            String path = homepage_detailsEntityList.get(i).getUrl();
            String homepage_title = homepage_detailsEntityList.get(i).getHomepage_title();
            String menu_id = homepage_detailsEntityList.get(i).getHomepage_id() + "";
            if (nodeId != null && nodeId.length() > 0) {
                try {
                    String url = "http://" + ip + ":" + port + "/cosmo-mmp/v1/resources/permissions?nodeId=" + nodeId + "&id=" + userId + "&type=user";
                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.APPLICATION_JSON);
                    headers.set("Authorization", "bearer" + token);
                    HttpEntity<JSONObject> httpEntity = new HttpEntity(headers);
                    ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
                    JSONObject bodyJson = JSONObject.fromObject(exchange.getBody());
                    JSONArray dataJsonList = bodyJson.getJSONArray("data");
                    for (int n = 0; n < dataJsonList.size(); n++) {
                        JSONObject dataJson = JSONObject.fromObject(dataJsonList.get(n));
                        if (dataJson.getString("permName").equals("显示")) {
                            if (dataJson.getInt("directPerm") == 1 || dataJson.getInt("userPerm") == 1 || dataJson.getInt("rolePerm") == 1 || dataJson.getInt("orgPerm") == 1) {
                                Map<String, Object> retMap = new HashMap<>();
                                retMap.put("nodeId", menu_id);
                                retMap.put("path", path);
                                retMap.put("flag", 1);
                                retMap.put("title", homepage_title);
                                returnList.add(retMap);
                            } else {
                                Map<String, Object> retMap = new HashMap<>();
                                retMap.put("nodeId", menu_id);
                                retMap.put("path", path);
                                retMap.put("flag", 0);
                                retMap.put("title", homepage_title);
                                returnList.add(retMap);
                            }
                        } else {
                            continue;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("code", 200);
        returnMap.put("data", returnList);
        JSONObject returnInfo = JSONObject.fromObject(returnMap);
        return returnInfo;
    }

    /**
     * 更新该用户nodeId
     *
     * @param json
     * @return
     */
    @Override
    public JSONObject updateHomeuser(String json) {
        System.out.println("updateHomeuser:" + json);
        try {
            JSONObject jsonBody = JSONObject.fromObject(json);
            JSONArray dataList = jsonBody.getJSONArray("data");
            JSONObject data1 = JSONObject.fromObject(dataList.getString(0));
            String userId1 = data1.getString("userId");
            home_userService.getBaseMapper().delete(new QueryWrapper<Home_userEntity>().eq("user_id", userId1));
            for (int i = 0; i < dataList.size(); i++) {
                JSONObject data = JSONObject.fromObject(dataList.getString(i));
                Home_userEntity home_userEntity = new Home_userEntity();
                home_userEntity.setUser_id(Integer.parseInt(data.getString("userId")));
                home_userEntity.setNumber(Integer.parseInt(data.getString("number")));
                home_userEntity.setNumber1(Integer.parseInt(data.getString("number1")));
                home_userEntity.setMenu_id(Integer.parseInt(data.getString("menuId")));
                home_userService.getBaseMapper().insert(home_userEntity);
            }
            Map<String, Object> retMap = new HashMap<>();
            retMap.put("code", 200);
            retMap.put("message", "success...");
            JSONObject jsonObject = JSONObject.fromObject(retMap);
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> retMap = new HashMap<>();
            retMap.put("code", 204);
            retMap.put("message", "error...");
            JSONObject jsonObject = JSONObject.fromObject(retMap);
            return jsonObject;
        }
    }


}
